package com.cangxuan.blockchain.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cangxuan.blockchain.bean.Result;
import com.cangxuan.blockchain.dto.CreateAccountDTO;
import com.cangxuan.blockchain.dto.Message;
import com.cangxuan.blockchain.service.IBlockChainService;
import com.cangxuan.blockchain.utils.AvataUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
@Slf4j
public class BlockChainServiceImpl implements IBlockChainService {
    private static final String CREATE_ACCOUNT_URL = "/v1beta1/account";
    @Value("${avata.url}")
    private String AVATA_URL;
    @Value("${avata.apiSecret}")
    private String AVATA_API_SECRET;
    @Value("${avata.apiKey}")
    private String AVATA_API_KEY;
    @Resource
    private RestTemplate restTemplate;
    Random random = new Random();

    @Override
    public CreateAccountDTO createAccount(String name,String operationId) {
        Long currentTime  = System.currentTimeMillis();
        // 请求body
        Map<String, Object> body = new HashMap<>();
        body.put("name", name);
        body.put("operation_id", operationId+""+random.nextInt(100)+1);
        // 验签
        String signature = AvataUtils.signRequest(CREATE_ACCOUNT_URL, null, body, currentTime, AVATA_API_SECRET);
        // 请求体
        HttpHeaders headers = getHttpHeader(signature, currentTime);
        headers.setContentType(MediaType.parseMediaType("application/json"));

        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(body), headers);

        String url = AVATA_URL + CREATE_ACCOUNT_URL;
        log.info("文昌链接口请求地址"+url);
        try {
            // 接口调用
            ParameterizedTypeReference<Message<CreateAccountDTO>> typeReference = new ParameterizedTypeReference<Message<CreateAccountDTO>>() {
            };
            ResponseEntity<Message<CreateAccountDTO>> responseEntity;
            responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, typeReference);

            Message<CreateAccountDTO> message = responseEntity.getBody();

            CreateAccountDTO createAccountDTO = message.getData();
            // 成功
            log.info("创建链账户成功:" + createAccountDTO);

            return createAccountDTO;
        } catch (Exception e) {
            return null;
        }
    }

    HttpHeaders getHttpHeader(String signature, Long timestamp) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Api-Key", AVATA_API_KEY);
        headers.set("X-Timestamp", timestamp.toString());
        headers.set("X-Signature", signature);

        return headers;
    }
}
